const path = require("path");
const ReactRefreshPlugin = require("@pmmmwh/react-refresh-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const EslintWebpackPlugin = require("eslint-webpack-plugin");

const cssRules = /\.css$/; // 匹配css
const lessRules = /\.less$/; // 匹配less

// 抽取公共部分
const getStyleOptions = (importLoaders, loader) => {
    return [
        "style-loader",
        {
            loader: "css-loader",
            options: {
                importLoaders
            }
        },
        "postcss-loader",
        loader
    ].filter(Boolean);
}

module.exports = {
    // 开发环境
    mode: "development",
    // 入口
    entry: "./src/index.js",
    // 配置loader
    module: {
        rules: [
            {
                // oneOf可以提供精准解析
                oneOf: [
                    {
                        test: cssRules,
                        use: getStyleOptions(1)
                    },
                    {
                        test: lessRules,
                        use: getStyleOptions(2, "less-loader")
                    },
                    {
                        test: /\.jsx?$/,
                        exclude: /node_modules/,
                        use: {
                            loader: "babel-loader",
                            options: {
                                // 开启缓存
                                cacheDirectory: true,
                                // 关闭压缩
                                cacheCompression: false
                            }
                        }
                    }
                ]
            }
        ]
    },
    plugins: [
        // 生成html模板
        new HtmlWebpackPlugin({
            // 以index.html文件为模板
            template: path.resolve(__dirname, "public/index.html")
        }),
        // 开启HMR功能
        new ReactRefreshPlugin(),
        // 开启eslint检查
        new EslintWebpackPlugin({
            // 检查jsx js json文件
            extensions: ["jsx", "js", "json"],
            // 只对修改内容的文件做检查
            lintDirtyModulesOnly: true,
            // 开启多线程
            threads: true
        })
    ],
    // 开启source-map，精准定位错误代码
    devtool: "cheap-module-source-map",
    // 开启开发服务器
    // hot: true是默认的，无需重复配置
    devServer: {
        port: 3001
    },
    resolve: {
        // 扩展文件名，引入时不需要写后缀
        extensions: [".jsx", ".js", ".json"]
    }
}